package cat.music.ut.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import cat.music.ut.CatApp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


abstract class BaseFragment<VBinding : ViewBinding> : Fragment() {

    //    private val loadingDialog by lazy { LoadingDialog(requireActivity()) }
    protected lateinit var binding: VBinding
    protected lateinit var vb: VBinding
    protected abstract fun getViewBinding(): VBinding

    val sp by lazy { CatApp.getInstance().getSp() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
        observe()
        initClick()
    }

    abstract fun initView()

    abstract fun observe()

    abstract fun initData()
    open fun initClick() {}
    private fun init() {
        binding = getViewBinding()
        vb = binding
//        vb.root.findViewById<View>(R.id.iv_back)?.apply {
//            setOnClickListener {
//                requireActivity().finish()
//            }
//        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    private val activity by lazy { requireActivity() as BaseActivity<*> }
    fun showLoading() {
        activity.showLoading()
    }

    fun showLoading(msg: String) {
        activity.showLoading(msg)
    }

    fun hideLoading() {
        activity.hideLoading()
    }

    override fun onDestroy() {
        super.onDestroy()
        hideLoading()
    }
    fun toast(msg:String){
        (requireActivity() as BaseActivity<*>).toast(msg)
    }
    fun withUI(block:()->Unit){
        lifecycleScope.launch(Dispatchers.Main){
            block.invoke()
        }
    }
}